<?php
include_once '../include/db.class.php';
include_once '../include/lxbase.class.php';
include_once '../include/wx.class.php';
if(!empty($_GET["code"])){
	$webconn=new Lxbase();
	$webinfo = Lxbase::getconfig("web");
	$code=$_GET["code"];
	$state=base64_decode($_GET["state"]);
	if(empty($state)){die("微信授权失败");}
	$parm = explode(",",$state);
	$url=$parm[0];
	$userid=$parm[1];
	$uid=$parm[2];
	$wxinfo = $webconn->viewdata("*","wxuser","where userid={$userid}");
	$json=$webconn->call_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".trim($wxinfo["appid"])."&secret=".trim($wxinfo["secret"])."&code={$code}&grant_type=authorization_code");
	$userinfo=json_decode($json,true);
	$openid=$userinfo["openid"];
	$token=$userinfo["access_token"];
	$rtoken=$userinfo["refresh_token"];
	$temurl="https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$uid}&lang=zh_CN";
	$getuinfo=json_decode($webconn->call_get($temurl),true);
	if(!empty($getuinfo["nickname"])){
		$uname=$getuinfo["nickname"];
		$uface=$getuinfo["headimgurl"];
	}
	$tokentim=time()+7200;
	$checkinfo=$webconn->viewdata("id","wxguest","where userid={$userid}");
	if(empty($checkinfo)){
		$into="openid='{$openid}',uid='{$uid}',uname='{$uname}',uface='{$uface}',token='{$token}',rtoken='{$rtoken}',userid={$userid},tokentim='{$tokentim}'";
		$webconn->setdata("wxguest",$into);
	}else{
		$into="uname='{$uname}',uid='{$uid}',uface='{$uface}',token='{$token}',rtoken='{$rtoken}',tokentim='{$tokentim}'";
		$webconn->updata("wxguest",$into,"where id={$checkinfo['id']}");
	}
	header("location:".$webinfo["basehost"].$url);
	exit;
}